package com.tencreat.service.mall.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.CollageStatus;
import com.tencreat.common.utils.TenCreatUtil;
import com.tencreat.domain.mall.*;
import com.tencreat.domain.mall.dto.MallGoodsCollageDTO;
import com.tencreat.domain.mall.dto.MallGoodsRecordDTO;
import com.tencreat.domain.mall.vo.*;
import com.tencreat.domain.mall.dto.GoodsCollageListAppDTO;
import com.tencreat.mapper.mall.MallCollectMapper;
import com.tencreat.mapper.mall.MallGoodsCollageMapper;
import com.tencreat.service.mall.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品拼团Service业务层处理
 *
 * @author tencreat
 * @date 2022-01-24
 */
@Service
public class MallGoodsCollageServiceImpl extends ServiceImpl<MallGoodsCollageMapper, MallGoodsCollage> implements IMallGoodsCollageService {

    @Autowired
    MallCollectMapper mallCollectMapper;
    @Autowired
    IMallAddressService mallAddressService;
    @Autowired
    IMallGoodsNormsService mallGoodsNormsService;
    @Autowired
    IMallGoodsCollageOrderService mallGoodsCollageOrderService;
    @Autowired
    IMallCategoryService categoryService;

    /**
     * 查询商品拼团
     *
     * @param id 商品拼团ID
     * @return 商品拼团
     */
    @Override
    public MallGoodsCollageVO selectMallGoodsCollageById(ReqIdParam id) {
        return baseMapper.getDetail(id.getId());
    }

    /**
     * 查询商品拼团列表
     *
     * @param mallGoodsCollage 商品拼团
     * @return 商品拼团
     */
    @Override
    public List<MallGoodsCollage> selectMallGoodsCollageList(MallGoodsCollage mallGoodsCollage) {
        return baseMapper.selectList(Wrappers.query(mallGoodsCollage));
    }

    /**
     * 新增商品拼团
     *
     * @param mallGoodsCollage 商品拼团
     * @return 结果
     */
    @Override
    public int insertMallGoodsCollage(MallGoodsCollage mallGoodsCollage) {
        mallGoodsCollage.setActiveSn(TenCreatUtil.getOrderNo());
        mallGoodsCollage.setSort(mallGoodsCollage.getSort());
        mallGoodsCollage.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(mallGoodsCollage);
    }

    /**
     * 修改商品拼团
     *
     * @param mallGoodsCollage 商品拼团
     * @return 结果
     */
    @Override
    public int updateMallGoodsCollage(MallGoodsCollage mallGoodsCollage) {
        mallGoodsCollage.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(mallGoodsCollage);
    }

    /**
     * 批量删除商品拼团
     *
     * @param ids 需要删除的商品拼团ID
     * @return 结果
     */
    @Override
    public int deleteMallGoodsCollageByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }

    /**
     * 删除商品拼团信息
     *
     * @param id 商品拼团ID
     * @return 结果
     */
    @Override
    public int deleteMallGoodsCollageById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }

    @Override
    public Page<MallGoodsCollageVO> PCPage(IPage<?> page, MallGoodsCollageDTO dto) {
        return baseMapper.PCPage(page, dto);
    }

    @Override
    public Page<ResGoodsCollageListAppVO> appPage(Page<ResGoodsCollageListAppVO> page, GoodsCollageListAppDTO vo) {
        if (vo.getTwoCategoryId() == 0 && vo.getOneCategoryId() != 0) {
            List<MallCategory> list = categoryService.list(new QueryWrapper<MallCategory>().eq("pid", vo.getOneCategoryId()));
            List<Long> longs = new ArrayList<>();
            for (MallCategory mallCategory : list) {
                longs.add(mallCategory.getId());
            }
            if (longs.size() > 0) {
                vo.setCategoryIds(longs);
            } else {
                return new Page<>(vo.getPageNum(), vo.getPageSize());
            }
        }
        Page<ResGoodsCollageListAppVO> appPage = baseMapper.appPage(page, vo, LocalDateTime.now());
        if (appPage != null && appPage.getRecords() != null && appPage.getRecords().size() >0){
            Map<Long,List<MallGoodsCollageOrder>> ingMap = null;
            Map<Long,List<MallGoodsCollageOrder>> succMap = null;
            // 查询正在拼团中的人数
            List<Long> collageIds = appPage.getRecords().stream().map(ResGoodsCollageListAppVO::getCollageGoodsId).collect(Collectors.toList());
            List<MallGoodsCollageOrder> list = mallGoodsCollageOrderService.lambdaQuery().in(MallGoodsCollageOrder::getCollageId, collageIds)
                    .eq(MallGoodsCollageOrder::getCollageStatus, CollageStatus.ING)
                    .ge(MallGoodsCollageOrder::getEndTime, LocalDateTime.now()).list();
            if (list != null && list.size() >0){
                ingMap = list.stream().collect(Collectors.groupingBy(MallGoodsCollageOrder::getCollageId));
            }
            // 拼团成功
            List<MallGoodsCollageOrder> list1 = mallGoodsCollageOrderService.lambdaQuery().in(MallGoodsCollageOrder::getCollageId, collageIds)
                    .eq(MallGoodsCollageOrder::getCollageStatus, CollageStatus.OK)
                    .list();
            if (list1 != null && list1.size() >0){
                succMap = list1.stream().collect(Collectors.groupingBy(MallGoodsCollageOrder::getCollageId));
            }
            Map<Long, List<MallGoodsCollageOrder>> finalIngMap = ingMap;
            Map<Long, List<MallGoodsCollageOrder>> finalSuccMap = succMap;
            appPage.getRecords().forEach(item->{
                if (finalIngMap != null && finalIngMap.get(item.getCollageGoodsId()) != null){
                    item.setNumberRemaining(finalIngMap.get(item.getCollageGoodsId()).size());
                }else {
                    item.setNumberRemaining(0);
                }
                if (finalSuccMap != null && finalSuccMap.get(item.getCollageGoodsId()) != null){
                    item.setNumberGet(finalSuccMap.get(item.getCollageGoodsId()).size());
                }else {
                    item.setNumberGet(0);
                }
            });
        }

        return appPage;
    }

    @Override
    public HttpResult<ResGoodsCollageDetailVO> getGoodsCollageById(ReqIdParam id, LoginUser loginCheck) {
        ResGoodsCollageDetailVO res = baseMapper.getGoodsCollageDetailById(id.getId());
        List<String> gallery = JSONObject.parseObject(res.getImage(), ArrayList.class);
        res.setGallery(gallery);
        res.setDetail(res.getImage2());
        //快递价
        if (null != id.getAddressId()) {
            BigDecimal postAgePrice = mallAddressService.getPostAgeByGood(res.getGoodsId(), id.getAddressId().intValue());
            res.setPostage(postAgePrice);
        } else {
            res.setPostage(new BigDecimal("0"));
        }

        MallGoodsNorms norms = mallGoodsNormsService.getFirstNorms(res.getGoodsId());
        res.setNormsId(norms.getId());
        res.setInventory(norms.getInventory());

        res.setIsCollect(mallCollectMapper.selectIsCollect(id.getId(), loginCheck.getAccountLogin().getId()) > 0);
        //查询待拼单用户
        res.setCollageOrder(mallGoodsCollageOrderService.lambdaQuery().eq(MallGoodsCollageOrder::getCollageStatus, CollageStatus.ING.getValue())
                .eq(MallGoodsCollageOrder::getSponsor, 1).eq(MallGoodsCollageOrder::getGoodsId, res.getGoodsId()).gt(MallGoodsCollageOrder::getEndTime, LocalDateTime.now()).list());
        return HttpResult.ok(res);
    }

    @Override
    public List<ResGoodsCollageListAppVO> getMyCollage(LoginUser loginCheck, Long collageStatus) {
        List<ResGoodsCollageListAppVO> myCollage = baseMapper.getMyCollage(loginCheck.getAccountLogin().getUuid(), collageStatus);
        if (myCollage !=null && myCollage.size() >0) {
            Map<Long, List<MallGoodsCollageOrder>> ingMap = null;
            Map<Long, List<MallGoodsCollageOrder>> succMap = null;
            // 查询正在拼团中的人数
            List<Long> collageIds = myCollage.stream().map(ResGoodsCollageListAppVO::getCollageGoodsId).collect(Collectors.toList());
            List<MallGoodsCollageOrder> list = mallGoodsCollageOrderService.lambdaQuery().in(MallGoodsCollageOrder::getCollageId, collageIds)
                    .eq(MallGoodsCollageOrder::getCollageStatus, CollageStatus.ING)
                    .ge(MallGoodsCollageOrder::getEndTime, LocalDateTime.now()).list();
            if (list != null && list.size() > 0) {
                ingMap = list.stream().collect(Collectors.groupingBy(MallGoodsCollageOrder::getCollageId));
            }
            // 拼团成功
            List<MallGoodsCollageOrder> list1 = mallGoodsCollageOrderService.lambdaQuery().in(MallGoodsCollageOrder::getCollageId, collageIds)
                    .eq(MallGoodsCollageOrder::getCollageStatus, CollageStatus.OK)
                    .list();
            if (list1 != null && list1.size() > 0) {
                succMap = list1.stream().collect(Collectors.groupingBy(MallGoodsCollageOrder::getCollageId));
            }
            Map<Long, List<MallGoodsCollageOrder>> finalIngMap = ingMap;
            Map<Long, List<MallGoodsCollageOrder>> finalSuccMap = succMap;
            myCollage.forEach(item -> {
                if (finalIngMap != null && finalIngMap.get(item.getCollageGoodsId()) != null) {
                    item.setNumberRemaining(finalIngMap.get(item.getCollageGoodsId()).size());
                } else {
                    item.setNumberRemaining(0);
                }
                if (finalSuccMap != null && finalSuccMap.get(item.getCollageGoodsId()) != null) {
                    item.setNumberGet(finalSuccMap.get(item.getCollageGoodsId()).size());
                } else {
                    item.setNumberGet(0);
                }
            });
        }
        return myCollage;
    }

    @Override
    public MallCollageCountVO collageCount() {
        MallCollageCountVO vo = new MallCollageCountVO();
        LocalDateTime now = LocalDateTime.now();

        // 拼团成功总金额
        BigDecimal collageSuccess = baseMapper.collageCount(1, null);
        vo.setCollageSuccess(collageSuccess);

        // 今日拼团成功总金额
        BigDecimal todayCollageSuccess = baseMapper.collageCount(1, now);
        vo.setTodayCollageSuccess(todayCollageSuccess);

        // 拼团失败总金额
        BigDecimal collageFail = baseMapper.collageCount(2, null);
        vo.setCollageFail(collageFail);

        // 今日拼团失败总金额
        BigDecimal todayCollageFail = baseMapper.collageCount(2, now);
        vo.setTodayCollageFail(todayCollageFail);
        return vo;
    }

    @Override
    public IPage<MallGoodsCollageRecordVo> collageRecord(IPage<?> iPage, MallGoodsRecordDTO dto) {
        return  baseMapper.collageRecord(iPage,dto);
    }

    /****
     * 上升
     * @param mallGoodsCollage
     * @return
     */
    @Override
    public boolean reSortOrderReduce(MallGoodsCollage mallGoodsCollage) {
        MallGoodsCollage one = lambdaQuery().eq(MallGoodsCollage::getId, mallGoodsCollage.getId()).one();
        one.setSort(one.getSort() -1);
        updateById(one);

        return true;
    }
    /****
     * 下降
     * @param mallGoodsCollage
     * @return
     */
    @Override
    public boolean reSortOrderPlus(MallGoodsCollage mallGoodsCollage) {
        MallGoodsCollage one = lambdaQuery().eq(MallGoodsCollage::getId, mallGoodsCollage.getId()).one();
        one.setSort(one.getSort() +1);
        updateById(one);

        return true;
    }
}
